﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;

namespace Common.Tools
{
    public class EMailHelper
    {
        /// <summary>
        /// 自己的姓名
        /// </summary>
        public string MyMailName { get; set; }
        /// <summary>
        /// 自己的邮箱地址
        /// </summary>
        public string MyMailAddr { get; set; }
        /// <summary>
        /// 自己邮箱密码
        /// </summary>
        public string MyMailCode { get; set; }
        /// <summary>
        /// 发送对方的邮箱地址
        /// </summary>
        public string SendMailAddr { get; set; }
        /// <summary>
        /// 发送的主题内容
        /// </summary>
        public string SendTilte { get; set; }
        /// <summary>
        /// 发送信箱的服务器
        /// </summary>
        public string SendingMailServer { get; set; }

        #region 验证Email格式
        /// <summary>
        /// 验证Email格式
        /// </summary>
        /// <param name="str">需要验证的对象</param>
        /// <returns></returns>
        public static bool EamilChangeVerify(string str)
        {
            string s = @"^(([0-9a-zA-Z]+)|([0-9a-zA-Z]+[_.0-9a-zA-Z-]*[0-9a-zA-Z]+))@([a-zA-Z0-9-]+[.])+([a-zA-Z]{2}|net|NET|com|COM|gov|GOV|mil|MIL|org|ORG|edu|EDU|int|INT)$";//正则表达式
            Regex re = new Regex(s);
            Match ma = re.Match(str);
            if (!ma.Success)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 验证配置的参数是否正确和完整
        /// <summary>
        /// 验证配置参数是否正确
        /// </summary>
        /// <returns></returns>
        public string PlacedNumber()
        {
            if (EamilChangeVerify(MyMailAddr) == false)
            {
                return "自己的邮箱地址格式不正确";
            }

            if (EamilChangeVerify(SendMailAddr) == false)
            {
                return "发送对方的邮箱地址格式不正确";
            }

            if (MyMailAddr == "")
            {
                return "自己的邮箱地址不能为空";
            }
            if (MyMailName == "")
            {
                return "自己的姓名不能为空";
            }
            if (MyMailCode == "")
            {
                return "自己邮箱密码";
            }
            if (SendTilte == "")
            {
                return "发送主题不能为空";
            }
            if (SendingMailServer == "")
            {
                return "发送信箱的服务器";
            }
            return "配置参数正确";
        }
        #endregion
        public EMailHelper()
        {
            MyMailName = "魔力邮箱";
            MyMailAddr = "moolly@imooly.com";
            MyMailCode = "ml2013";
            SendTilte = "魔力邮箱验证";
            SendMailAddr = "";
            SendingMailServer = "smtp.exmail.qq.com";
        }


        /// <summary>
        /// 发送的内容，发送成功，返回的是"发送成功"字符串
        /// </summary>
        /// <param name="sendBody"></param>
        /// //发送邮件的内容
        /// <returns></returns>
        public bool SendEmail(string sendBody)//发激活码邮件部分 
        {
            try
            {
                string strResults = PlacedNumber();
                if (strResults != "配置参数正确")
                {
                    return false;
                }
                //编码暂硬性规定为GB2312 
                Encoding encoding = Encoding.GetEncoding(936);
                var message = new MailMessage(new MailAddress(MyMailAddr, MyMailName, encoding),//第一个是发信人的地址，第二个参数是显示的发信人
                new MailAddress(SendMailAddr))
                {
                    SubjectEncoding = encoding,
                    Subject = SendTilte,
                    BodyEncoding = encoding,
                    IsBodyHtml = true,
                    Body = sendBody
                };//收信人邮箱

                var smtpClient = new SmtpClient(SendingMailServer)
                {
                    Credentials = new NetworkCredential(MyMailAddr, MyMailCode),
                    Timeout = 100000
                };//信箱服务器 
                smtpClient.Send(message);
            }
            catch
            {
                //throw new Exception(ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 发送的内容加附件，发送成功，返回的是"发送成功"字符串
        /// </summary>
        /// <param name="sendBody"></param>//发送邮件的内容
        /// <param name="filePath"></param>//附件的路径
        /// <returns></returns>
        public bool SendEmail(string sendBody, List<string> filePath)//发激活码邮件部分 
        {
            try
            {
                string strResults = PlacedNumber();
                if (strResults != "配置参数正确")
                {
                    return false;
                }
                //编码暂硬性规定为GB2312 
                Encoding encoding = Encoding.GetEncoding(936);
                var message = new MailMessage(new MailAddress(MyMailAddr, MyMailName, encoding),//第一个是发信人的地址，第二个参数是显示的发信人
                new MailAddress(SendMailAddr))
                {
                    SubjectEncoding = encoding,
                    Subject = SendTilte,
                    BodyEncoding = encoding,
                    IsBodyHtml = true,
                    Body = sendBody
                };//收信人邮箱
                if (filePath != null)
                {
                    foreach (var file in filePath)
                    {
                        if (!File.Exists(file)) continue;
                        var data = new Attachment(file, MediaTypeNames.Application.Octet);
                        ContentDisposition disposition = data.ContentDisposition;
                        disposition.CreationDate = File.GetCreationTime(file);
                        disposition.ModificationDate = File.GetLastWriteTime(file);
                        disposition.ReadDate = File.GetLastAccessTime(file);
                        message.Attachments.Add(data);
                    }
                }

                //for (int i = 0; i < FilePath.Count; i++)
                //{                    
                //    Message.Attachments.Add(new Attachment(FilePath[i]));
                //}
                var smtpClient = new SmtpClient(SendingMailServer)
                {
                    Credentials = new NetworkCredential(MyMailAddr, MyMailCode),
                    Timeout = 100000
                };//信箱服务器 
                smtpClient.Send(message);
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                return false;
            }
            return true;
        }

        public bool SendEmail(string sendBody, string filePath)//发激活码邮件部分 
        {
            try
            {
                string strResults = PlacedNumber();
                if (strResults != "配置参数正确")
                {
                    return false;
                }
                //编码暂硬性规定为GB2312 
                Encoding encoding = Encoding.GetEncoding(936);
                var message = new MailMessage(new MailAddress(MyMailAddr, MyMailName, encoding),//第一个是发信人的地址，第二个参数是显示的发信人
                new MailAddress(SendMailAddr))
                {
                    SubjectEncoding = encoding,
                    Subject = SendTilte,
                    BodyEncoding = encoding,
                    IsBodyHtml = true,
                    Body = sendBody
                };//收信人邮箱
                if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                {
                    var data = new Attachment(filePath, MediaTypeNames.Application.Octet);
                    ContentDisposition disposition = data.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(filePath);
                    disposition.ModificationDate = File.GetLastWriteTime(filePath);
                    disposition.ReadDate = File.GetLastAccessTime(filePath);
                    message.Attachments.Add(data);
                }

                //for (int i = 0; i < FilePath.Count; i++)
                //{                    
                //    Message.Attachments.Add(new Attachment(FilePath[i]));
                //}
                var smtpClient = new SmtpClient(SendingMailServer)
                {
                    Credentials = new NetworkCredential(MyMailAddr, MyMailCode),
                    Timeout = 100000
                };//信箱服务器 
                smtpClient.Send(message);
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                return false;
            }
            return true;
        }
    }
}
